package com.htandroid.htandroid.aty;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import com.ab.soap.AbSoapListener;
import com.ab.soap.AbSoapParams;
import com.ab.soap.AbSoapUtil;
import com.ab.util.AbToastUtil;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.sys.InstorageURL;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

/**
 * 自定义接收器
 *
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class JiGuangReceiver extends BroadcastReceiver {
    private static final String TAG = "pushreceiver";
    private AbSoapUtil mAbSoapUtil = null;

    @Override
    public void onReceive(final Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            //Logger.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                RefDeviceLogTime(context);
            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                //Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                String content = bundle.getString(JPushInterface.EXTRA_MESSAGE);
                String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
                String title = bundle.getString(JPushInterface.EXTRA_TITLE);
                //processCustomMessage(context, bundle);
                if (!content.equals("") && content != null) {
                    //有消息内容时则进行提示
                    receivingNotification(context, title, content, extra);
                }
                //生存信号处理
                RefDeviceLogTime(context);
            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                //Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知");
                int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                RefDeviceLogTime(context);
                //Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                //Logger.d(TAG, "[MyReceiver] 用户点击打开了通知");

                //打开自定义的Activity
                Intent i = new Intent(context, Login_choose.class);
                i.putExtras(bundle);
                //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                context.startActivity(i);

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                //Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                //Logger.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
            } else {
                //Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e){

        }
    }
    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            }else if(key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)){
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    //Logger.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it =  json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " +json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    //Logger.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }
/*
    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
        if (MainActivity.isForeground) {
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
            msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
            if (!JiGuangUtil.isEmpty(extras)) {
                try {
                    JSONObject extraJson = new JSONObject(extras);
                    if (extraJson.length() > 0) {
                        msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
                    }
                } catch (JSONException e) {

                }

            }
            LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
        }
    }*/
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void receivingNotification(Context context,String title, String message,String extras) {
        String extradata = "";
        Integer smsgtype = 0;
        if (!JiGuangUtil.isEmpty(extras)){
            JSONObject json1 = null;
            try {
                json1 = new JSONObject(extras);
                extradata = json1.getString("openmenu");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if(extradata.equals("qgddjlist")){
            smsgtype = 2;//消息提示类型
        }else if (extradata.equals("qgdsplist")){
            smsgtype = 3;//消息提示类型
         }else if (extradata.equals("mrqgdsplist") || (extradata.equals("mrqgdchecklist"))){
            //厨房请购审批或者厨房请购审核
            smsgtype = 11;//消息提示类型
        }else if (extradata.equals("mrqgdlist")){
            smsgtype = 12;//消息提示类型
         }else if (extradata.equals("kcapplist")){
            smsgtype = 13;//消息提示类型
         }else if (extradata.equals("wxjdlist")){
            smsgtype = 7;//消息提示类型
         }else if (extradata.equals("wxchecklist")){
            smsgtype = 8;//消息提示类型
        }
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = R.drawable.ic_launcher;
        Notification notification = new Notification();
        //notification.icon = R.drawable.ic_launcher;
        //设置浮现的提示内容
        Notification.Builder builder = new Notification.Builder(context).setTicker(message)
                .setSmallIcon(icon);
        //设置消息点击之后打开的窗口
        Intent notificationIntent = GetNotificationAction(context,extradata);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,notificationIntent, 0);
        //设置消息提示
        //notification.flags=Notification.FLAG_AUTO_CANCEL;//设置自动取消
        notification = builder.setContentIntent(contentIntent)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_SOUND).build();
        mNotificationManager.notify(smsgtype, notification);
        /*
        NotificationManager manager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        // 使用notification
        // 使用广播或者通知进行内容的显示
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                context);
        builder.setContentText(message).setSmallIcon(R.drawable.ic_launcher).setContentTitle("合泰软件");
        builder.setDefaults(Notification.DEFAULT_SOUND);
        manager.notify(1,builder.build());*/
    }

    //点击消息之后，激活软件。不进行定位
    public Intent GetNotificationAction(Context context,String menuauth) {
        /*if (menuauth.equals("qgddjlist")) {
            //部门请购定价
            return new Intent(context, qgddj_detail.class);
        } else if (menuauth.equals("qgdsplist")) {
            //部门请购审批
            return new Intent(context, qgdsp_detail.class);
        } else if (menuauth.equals("mrqgdsplist")) {
            //厨房请购审批
            return new Intent(context, mrqgdsp_detail.class);
        } else if (menuauth.equals("mrqgdlist")) {
            //厨房请购叫货，定价
            return new Intent(context, mrqgd_orderdetail.class);
        } else if (menuauth.equals("kcapplist")) {
            //功能：库存申请审批
            return new Intent(context, kcapp_detail.class);
        } else if (menuauth.equals("wxbxlist")) {
            //部门报修
            return new Intent(context,Gcwx_lr_detail.class);
        } else if (menuauth.equals("wxjdlist")) {
            //维修接单
            return new Intent(context,Gcwx_jd_detail.class);
        } else if (menuauth.equals("wxxdlist")) {
            //维修销单
            return new Intent(context,Gcwx_xd_detail.class);
        } else if (menuauth.equals("wxchecklist")) {
            //维修审核
            return new Intent(context,Gcwx_check_detail.class);
        } else if (menuauth.equals("zcpdlist")) {
            //资产盘点
            return new Intent(context,zcpd_detail.class);
        }*/
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setComponent(new ComponentName(context, MainActivity.class));//用ComponentName得到class对象
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);// 关键的一步，设置启动模式，两种情况
        return intent;
    }
    public static boolean isTop(Context context, Intent intent) {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> appTask = am.getRunningTasks(1);
        if (appTask.size() > 0 && appTask.get(0).topActivity.equals(intent.getComponent())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * @Description: TODO 判断应用是否在运行
     * @param context 上下文
     * @param intent intent携带activity
     * @return boolean true为在运行，false为已结束
     * @author Sunday
     * @date 2016年3月15日
     */
    public static boolean isRuning(Context context, Intent intent) {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks.size() > 0 && tasks.get(0).baseActivity.equals(intent.getComponent())) {
            return true;
        } else {
            return false;
        }
    }
    //更新上次时间
    private void RefDeviceLogTime(final Context context) {
        mAbSoapUtil = AbSoapUtil.getInstance(context);
        mAbSoapUtil.setTimeout(10000);

        String regId1 = JPushInterface.getRegistrationID(context);
//        TreeMap<String, String> properties = new TreeMap<String, String>();
//        properties.put("arg0", regId1);
//        ToolSOAP.callService(InstorageURL.SERVERURL, InstorageURL.NAME_SPACE, "DeviceLogTime", properties, new ToolSOAP.WebServiceCallBack() {
//            @Override
//            public void onSucced(SoapObject result) {
//                //loadingDialog.loadingfinish();
//                if (result != null) {
//                    String res = result.getProperty(0).toString();
//                } else {
//                    Toast.makeText(context, "设备已被注销", Toast.LENGTH_SHORT).show();
//                }
//            }
//
//            @Override
//            public void onFailure(String result) {
//                //loadingDialog.loadingfinish();
//                Toast.makeText(context, "数据库返回信息错误", Toast.LENGTH_SHORT).show();
//            }
//        });

        String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;
        String nameSpace = "http://service.test.com";
        String methodName = "DeviceLogTime";
        AbSoapParams params = new AbSoapParams();
        params.put("arg0", regId1);
        mAbSoapUtil.call(urlString, nameSpace, methodName, params, new AbSoapListener() {
            //获取数据成功会调用这里
            @Override
            public void onSuccess(int statusCode, String content) {
                if (content != null) {

                } else {
                    AbToastUtil.showToast(context, "设备已被注销");
                }
            }

            // 失败，调用
            @Override
            public void onFailure(int statusCode, String content,
                                  Throwable error) {

            }

            // 开始执行前
            @Override
            public void onStart() {
                //显示进度框
                //AbDialogUtil.showProgressDialog(context, 0, "正在加载...");
            }

            // 完成后调用，失败，成功
            @Override
            public void onFinish() {
                AbToastUtil.showToast(context, R.string.sqlerrormsg);
                //移除进度框
                //AbDialogUtil.removeDialog(context);
            }
        });
    }
}
